﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Google.GData.Client;
using Google.GData.Documents;
using Google.Documents;
using System.IO;
using Foundation;
using BusinessEntity.Data;

namespace BusinessEntity
{
    public class GDocsWrapper : GDocsBase
    {
        //private GDataCredentials credentials;

        //private List<Document> mAllDocument;
        private DocumentsRequest request;

        private DSFile mAllDSFile;

        public GDocsWrapper()
        {
            //mAllDocument = new List<Document>();
            mAllDSFile = new DSFile();
        }

        //public List<Document> AllDocument
        //{
        //    get { return mAllDocument; }
        //}

        public DSFile AllDSFile
        {
            get { return mAllDSFile; }
        }

        public void Login()
        {
            string lsUsername = "";
            string lsPassword = "";

            string lsEncUsername = "";
            string lsEncPassword = "";

            Utils.ReadRegistry(out lsEncUsername, out lsEncPassword);

            Encryptor lEncryptor = new Encryptor();

            if (lsEncUsername.Length > 0 && lsEncPassword.Length > 0)
            {

                lsUsername = lEncryptor.Decrypto(lsEncUsername);
                lsPassword = lEncryptor.Decrypto(lsEncPassword);
            }
            else
            {
                throw new Exception("Invalid Username/Password");
            }

            Constant.GCredentials = new GDataCredentials(lsUsername, lsPassword);
        }

        public void GetGDocsList()
        {
            int i;

            CreateLoginRequiredEvent();

            RequestSettings settings = new RequestSettings(Constant.ApplicationName, Constant.GCredentials);
            settings.AutoPaging = true;
            settings.PageSize = 100;
            if (settings != null)
            {
                this.request = new DocumentsRequest(settings);
                
                Feed<Document> feed = this.request.GetDocuments();
                
                // this takes care of paging the results in
                //mAllDocument.Clear();

                System.Data.DataRow[] ladr = mAllDSFile.DTFile.Select("DocListType='" + DocListTypeEnum.Remote.ToString() + "'");

                for (i = 0; i < ladr.Length; i++)
                {
                    ladr[i].Delete();
                }

                foreach (Document entry in feed.Entries)
                {
                    //mAllDocument.Add(entry);
                    mAllDSFile.DTFile.AddDTFileRow(DocListTypeEnum.Remote.ToString(), entry.Title, entry);
                }

                //TreeNode noFolder = null;
                //noFolder = new TreeNode("Items with no folder");
                //this.documentsView.Nodes.Add(noFolder);
                //noFolder.SelectedImageIndex = 0;
                //noFolder.ImageIndex = 0;

                //foreach (Document entry in all)
                //{
                        

                    //    // let's add those with no parents for the toplevel
                    //    if (entry.ParentFolders.Count == 0)
                    //    {
                    //        if (entry.Type != Document.DocumentType.Folder)
                    //        {
                    //            AddToTreeView(noFolder.Nodes, entry);
                    //        }
                    //        else
                    //        {
                    //            TreeNode n = AddToTreeView(this.documentsView.Nodes, entry);
                    //            AddAllChildren(n.Nodes, entry);
                    //        }

                    //    }

                //}
            }
        }

        public void GetDocsList()
        {
            try
            {
                int i;
                FileInfo[] lFileInfo = GDocs.GetLocalDocsList();

                System.Data.DataRow[] ladr = mAllDSFile.DTFile.Select("DocListType='" + DocListTypeEnum.Local.ToString() + "'");

                for (i = 0; i < ladr.Length; i++)
                {
                    ladr[i].Delete();
                }

                for (i = 0; i < lFileInfo.Length; i++)
                {
                    mAllDSFile.DTFile.AddDTFileRow(DocListTypeEnum.Local.ToString(), lFileInfo[i].Name, lFileInfo[i]);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Download(Document lDocument)
        {
            CreateLoginRequiredEvent();

            if (!Directory.Exists(Constant.GDocsLocalRoot))
            {
                Directory.CreateDirectory(Constant.GDocsLocalRoot);
            }

            RequestSettings settings = new RequestSettings(Constant.ApplicationName, Constant.GCredentials);
            
            settings.AutoPaging = true;
            settings.PageSize = 100;
            
            this.request = new DocumentsRequest(settings);
            Stream stream = request.Download(lDocument, Document.DownloadType.rtf);
            string outFileFP = Constant.GDocsLocalRoot + lDocument.Title + "." + Document.DownloadType.rtf.ToString();
            using (FileStream outFile = new FileStream(outFileFP, FileMode.Create, FileAccess.Write))
            {
                byte[] buffer = new byte[8192];
                int bytesRead;
                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                    outFile.Write(buffer, 0, bytesRead);
                outFile.Flush();
                outFile.Close();
            }
            //new FileInfo(outFileFP).LastWriteTime = entry.Updated;

            stream.Close();
        }

        public void Upload(FileInfo lFileInfo)
        {
            CreateLoginRequiredEvent();
            DocumentsService service = new DocumentsService(Constant.ApplicationName);
            service.Credentials = Constant.GCredentials;
            ((GDataRequestFactory)service.RequestFactory).KeepAlive = false;

            service.UploadDocument(lFileInfo.FullName, null);
            //service.UploadDocument(lFileInfo.FullName, Path.GetFileNameWithoutExtension(lFileInfo.FullName));

            
        }

        public void Delete(Document lDocument)
        {
            CreateLoginRequiredEvent();
            lDocument.DocumentEntry.Delete();

            //DocumentsService service = new DocumentsService(Constant.ApplicationName);

            //service.Credentials = Constant.GCredentials;
            //((GDataRequestFactory)service.RequestFactory).KeepAlive = false;

            //service.Delete(lDocument.AtomEntry);
        }

    }
}

